<template>
  <div class="UserConfig">
    <div class="left_table">
      <userList ref="user" @checkRole="checkRole"></userList>
    </div>
    <div class="right_content">
      <div class="top_menu">
        <div class="menu_left">
          <div class="check_item" @click="checkMenu(item)" v-for="(item, index) in checkList"
            :class="rolCheckId === item.id ? 'checkColor' : ''" :key="index">{{ item.name }}</div>
        </div>
      </div>
      <div class="bottom_main">
        <div class="details_box" v-show="rolCheckId === 1">
          <el-form style="display: flex;flex-direction: column;justify-content: center;align-items: center;" :model="form"
            label-width="120px" :rules="rules">
            <el-form-item label="角色名称：" prop="roleName">
              <el-input clearable v-model="form.roleName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="角色编码：" prop="roleCode">
              <el-input clearable v-model="form.roleCode" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="描述：" prop="description">
              <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="form.description">
              </el-input>
            </el-form-item>
            <el-button type="primary" @click="roleSave">保存</el-button>
          </el-form>
        </div>
        <div class="user_box" v-show="rolCheckId === 2">
          <div class="top_serch">
            <div class="serch_leftForm">
              <el-form style="display: flex;flex-wrap: wrap;justify-content: space-around;align-items: center;"
                :model="userForm" label-width="100px">
                <el-form-item label="机构名称：" prop="orgName">
                  <el-input clearable v-model="userForm.orgName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="账户名称：" prop="accountName">
                  <el-input clearable v-model="userForm.accountName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="角色名称：" prop="roleName">
                  <el-input clearable v-model="userForm.roleName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="账号：" prop="realName">
                  <el-input clearable v-model="userForm.realName" placeholder="请输入"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="serch_rightBtn">
              <el-button type="primary" @click="query">查询</el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </div>
          <div class="userList_content">
            <LsdTable slot="yjrwlb" :paginationAtrrs="table.paginationAtrrs" @pageChange="handleSizeChange"
              :compRef="table.compRef" ref="yjrwlb" :columns="table.columns" :title="table.title" :actions="table.actions"
              :tableData="table.tableData" :tableAttr="table.tableAttr" :isShowPage="table.isShowPage"
              :isSelectFlag="table.isSelectFlag" :isSequenceFlag="table.isSequenceFlag" @onActionClick="onActionClick" />
          </div>
        </div>
        <div class="menu_box" v-show="rolCheckId === 3">
          <div class="menu_tree">
            <div class="tree_box">
              <el-tree accordion ref="tree" @check="handleCheckTree" :current-node-key="defaultCheck" node-key="id"
                :default-expanded-keys="defaultShowNodes" :props="defaultProps" :check-strictly="true" :data="data"
                show-checkbox>
              </el-tree>
            </div>
            <div style="width: 50%;height: 10%;display: flex;justify-content: center;align-items: center;">
              <el-button type="primary" @click="zzjgSave">保存</el-button>
            </div>
          </div>
        </div>
        <div class="btnPower" v-show="rolCheckId === 4">
          <div class="tree_box">
            <el-tree ref="btnTree" @node-click="handleNodeClick" highlight-current accordion
              :current-node-key="defaultCheck" :default-expanded-keys="defaultShowNodes" node-key="id"
              :props="defaultProps" :data="data">
            </el-tree>
          </div>
          <div class="draggable_box">
            <div class="draggable_title">当前按钮权限</div>
            <div class="nowBox" @dragover.prevent @drop="drop('box1')">
              <div class="item" v-for="item in box1" :key="item.id" @dragstart="dragStart(item, 'box1')" draggable="true">
                {{ item.btnName }}</div>
            </div>
            <div class="draggable_title">可选按钮权限</div>
            <div class="boxList" @dragover.prevent @drop="drop('box2')">
              <div class="items" v-for="item in box2" :key="item.id" @dragstart="dragStart(item, 'box2')"
                draggable="true">
                {{ item.btnName }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <LsdDialog @handleBtn="onActionClick" :dialogConfig="dialogConfig" @close="close(dialogConfig)">
      <LsdTable v-if="dialogConfig.isShow" slot="dialog" :paginationAtrrs="table1.paginationAtrrs"
        @pageChange="handleSizeChange" :compRef="table1.compRef" ref="role" :columns="table1.columns"
        :title="table1.title" :actions="table1.actions" :tableData="table1.tableData" :tableAttr="table1.tableAttr"
        :isShowPage="table1.isShowPage" :isSelectFlag="table1.isSelectFlag" :isSequenceFlag="table1.isSequenceFlag"
        @onActionClick="onActionClick" />
    </LsdDialog>
  </div>
</template>

<script>
import { roleDetail, roleEdit, roleAccount, accountConcatRloe, deleteRoleAccount } from "@/api/SystemConfig/roleConfig";
import { accountList } from "@/api/SystemConfig/userConfig";
import userList from "../components/userList.vue";
import { menuTree, batchSave, getMenusByRoleId, getBtnByMenuId, saveMenuRoleComponent, getBtns } from "@/api/SystemConfig/menuConfig.js";
export default {
  components: {
    userList
  },
  data() {
    return {
      radio: "1",
      box1: [],
      box2: [],
      defaultBtnList: [],
      checkList: [
        {
          name: "明细",
          id: 1
        },
        {
          name: "角色下账户",
          id: 2
        },
        {
          name: "菜单权限",
          id: 3
        },
        {
          name: "按钮权限",
          id: 4
        }
      ],
      rolCheckId: Number(sessionStorage.getItem("rolCheckId")) || 1,
      form: {
        roleName: "",
        roleCode: "",
        description: ""
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleCode: [
          { required: true, message: "请输入角色编码", trigger: "blur" }
        ]
      },
      userForm: {
        orgName: "",
        accountName: "",
        roleName: "",
        realName: ""
      },
      // 列表表格
      table: {
        isSelectFlag: true,
        compRef: "yjrwlb",
        isSequenceFlag: true,
        isShowPage: false,
        resetFlag: true,
        loading: false,
        title: "",
        actions: [
          {
            id: "add",
            text: "新增",
            type: "primary",
            btnAttr: { size: "small" }
          }
        ],
        tableData: [],
        columns: [
          {
            prop: "orgName",
            label: "机构名称",
            align: "center"
          },
          {
            prop: "accountName",
            label: "账户名称",
            align: "center"
          },
          {
            prop: "realName",
            label: "账号",
            align: "center"
          },
          {
            prop: "roleName",
            label: "角色名称",
            align: "center"
          },
          {
            prop: "cz",
            label: "操作",
            align: "center",
            fixed: "right",
            "min-width": "120px",
            render: (h, scope) => {
              const arr = ["删除"];
              return (
                <div>
                  {
                    arr.map(item => {
                      return (
                        <span style='color:#3561fd;cursor:pointer;margin:0 10px' {...{
                          on: {
                            click: () => {
                              this.actionHandle(item, scope);
                            }
                          }
                        }}>
                          {item}
                        </span>
                      );
                    })
                  }
                </div >
              );
            }
          }

        ],
        tableAttr: {
          "min-height": `${window.innerHeight - (window.innerHeight * 0.455)}px`,
          height: `${window.innerHeight - (window.innerHeight * 0.455)}px`,
          stripe: false,
          border: true,
          fit: true,
          "show-header": true,
          "highlight-current-row": true,
          "cell-style": {
            "font-size": "16px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            border: "1px solid #ccc",
            color: "#333333",
            "font-size": "18px"
          }
        },
        // 分页信息
        paginationAtrrs: {
          total: 0,
          "background": true,
          layout: "prev, pager, next",
          "current-page": 1,
          "page-size": 10
        }
      },
      dialogConfig: {
        title: "账号选择",
        isShow: false,
        type: "",
        btnList: [
          {
            name: "确定",
            type: "primary",
            id: "submit",
            size: "mini"
          },
          {
            name: "取消",
            id: "cancel",
            size: "mini"
          }
        ],
        width: "40%"
      },
      table1: {
        isSelectFlag: true,
        compRef: "yjrwlb",
        isSequenceFlag: true,
        isShowPage: true,
        resetFlag: true,
        loading: false,
        title: "",
        actions: [],
        tableData: [],
        columns: [
          {
            prop: "accountName",
            label: "账户名称",
            align: "center"
          },
          {
            prop: "realName",
            label: "账号",
            align: "center"
          },
          {
            prop: "orgName",
            label: "所属机构",
            align: "center"
          },
          {
            prop: "roleName",
            label: "角色名称",
            align: "center"
          }
        ],
        tableAttr: {
          // "min-height": `${window.innerHeight - (window.innerHeight * 0.1)}px`,
          // height: `${window.innerHeight - (window.innerHeight * 0.1)}px`,
          stripe: false,
          border: true,
          fit: true,
          "show-header": true,
          "highlight-current-row": true,
          "cell-style": {
            "font-size": "16px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            border: "1px solid #ccc",
            color: "#333333",
            "font-size": "18px"
          }
        },
        // 分页信息
        paginationAtrrs: {
          total: 0,
          "background": true,
          layout: "prev, pager, next",
          "current-page": 1,
          "page-size": 10
        }
      },
      defaultProps: {
        children: "children",
        label: "menuName",
        value: "id"
      },
      data: [],
      defaultShowNodes: [1],
      defaultCheck: 1
    };
  },
  computed: {},
  watch: {},
  methods: {
    allowDrop(event) {
      event.preventDefault();
    },
    dragStart(item, sourceBox) {
      event.dataTransfer.setData("text/plain", JSON.stringify({ item, sourceBox }));
    },
    async drop(targetBox) {
      const data = JSON.parse(event.dataTransfer.getData("text/plain"));
      const { item, sourceBox } = data;
      // 从源盒子中移除元素
      const sourceItems = sourceBox === "box1" ? this.box1 : this.box2;
      const sourceIndex = sourceItems.findIndex((i) => i.id === item.id);
      if (targetBox != sourceBox) {
        // 从源盒子中移除元素
        sourceItems.splice(sourceIndex, 1);
        const targetItems = targetBox === "box1" ? this.box1 : this.box2;
        // 将元素添加到目标盒子
        targetItems.push(item);
        const params = {
          menuId: this.menuId,
          roleId: this.roleId,
          btn: this.box1
        };
        const res = await saveMenuRoleComponent(params);
        if (targetBox === "box1" && res) {
          this.$message({
            message: "添加成功!",
            type: "success"
          });
        } else if (targetBox === "box2" && res) {
          this.$message({
            message: "移出成功!",
            type: "success"
          });
        }
      }
    },
    async getBtnPower(id) {
      const res = await getBtnByMenuId(id);
      this.box2 = res || [];
      this.defaultBtnList = res || [];
    },
    async getBtnsByRole(roleId, menuId) {
      const params = {
        roleId,
        menuId
      };
      const res = await getBtns(params);
      this.box1 = res;
      this.box2 = this.defaultBtnList;
      if (res) {
        this.box2 = this.box2.filter((i) => {
          return !this.box1.some((j) => {
            return j.id === i.id;
          });
        });
      }
    },
    handleNodeClick(data, node, item) {
      this.getBtnPower(data.id);
      this.menuId = data.id;
      setTimeout(() => {
        this.getBtnsByRole(this.roleId, data.id);
      }, 500);
    },
    roleSave() {
      const params = {
        id: this.roleId,
        ...this.form
      };
      roleEdit(params).then(res => {
        if (res) {
          this.$message({
            message: "修改成功!",
            type: "success"
          });
          this.$refs.user.getRoleList();
        }
      });
    },
    checkRole(id, row) {
      this.roleId = id;
      const rolCheckId = Number(sessionStorage.getItem("rolCheckId")) || 1;
      if (rolCheckId === 1) {
        roleDetail({ id: id }).then(res => {
          this.form = { ...res };
        });
      } else if (rolCheckId === 2) {
        this.getRoleAccount(id);
      } else if (rolCheckId === 3) {
        this.getMenuTree();
        this.getRoleWithMenu();
      } else {
        this.getMenuTree();
      }

    },
    checkMenu(item) {
      this.rolCheckId = item.id;
      sessionStorage.setItem("rolCheckId", item.id);
      if (this.roleId) {
        if (this.rolCheckId === 1) {
          this.checkRole(this.roleId);
        } else if (this.rolCheckId === 2) {
          this.getRoleAccount(this.roleId);
        } else if (this.rolCheckId === 3) {
          this.getMenuTree();
          this.getRoleWithMenu();
        } else {
          this.getMenuTree();
        }
      } else {
        this.$message({
          message: "请选择一条角色数据!",
          type: "warning"
        });
      }
    },
    // 获取当前角色下账户
    getRoleAccount(id) {
      const params = {
        roleId: id,
        ...this.userForm
      };
      roleAccount(params).then(res => {
        this.table.tableData = res;
      });
    },
    query() {
      this.getRoleAccount(this.roleId);
    },
    reset() {
      this.userForm = {};
      this.getRoleAccount(this.roleId);
    },
    close(val) {
      val.isShow = false;
    },
    onActionClick(item) {
      this[item.id]();
    },
    // 用户新增
    add(val) {
      console.log(this.roleId);
      if (this.roleId) {
        this.dialogConfig.isShow = true;
        let params = {};
        if (val) {
          params = {
            ...val
          };
        } else {
          params = {
            pageNum: 1,
            pageSize: 10
          };
          this.$set(this.table1.paginationAtrrs, "current-page", 1);
          this.$set(this.table1.paginationAtrrs, "page-size", 10);
        }
        accountList(params).then(res => {
          this.table1.tableData = res.data;
          this.table1.paginationAtrrs.total = res.total;
        });
      } else {
        this.$message({
          message: "请选择一条角色数据!",
          type: "warning"
        });
      }
    },
    submit() {
      const params = {
        roleId: this.roleId,
        userId: this.$refs.role.selection[0].id
      };
      accountConcatRloe(params).then(res => {
        if (res) {
          this.$message({
            message: "关联成功!",
            type: "success"
          });
          this.dialogConfig.isShow = false;
          this.getRoleAccount(this.roleId);
        }
      });
    },
    // 删除角色下账号
    actionHandle(item, scope) {
      if (item === "删除") {
        const params = {
          userId: scope.row.id,
          roleId: this.roleId
        }; this.$confirm("此操作将永久删除该账户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteRoleAccount(params).then(res => {
            if (res) {
              this.$message({
                message: "删除成功!",
                type: "success"
              });
              this.getRoleAccount(this.roleId);
            }
          });
        })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });

      }
    },
    // 分页
    handleSizeChange(val) {
      if (this.dialogConfig.isShow) {
        const params = {
          pageNum: val["current-page"],
          pageSize: val["page-size"]
        };
        this.add(params);
      }
    },
    async getMenuTree() {
      const res = await menuTree();
      const result = Object.assign([], res[0].children);
      this.data = result.filter(i => !["PC端", "运维端", "test"].includes(i.menuName));
      // this.data = result;
      if (this.rolCheckId === 4) {
        //   console.log(this.$refs.btnTree);
        //   this.$refs.btnTree.setCheckedKeys(this.data[0].id);
        this.getBtnPower(this.data[0].id);
        this.menuId = this.data[0].id;
        setTimeout(() => {
          this.getBtnsByRole(this.roleId, this.data[0].id);
        }, 500);
      }
    },
    // 菜单树点击事件
    handleCheckTree(data, { checkedKeys }) {
      if (checkedKeys.includes(data.id)) { // 选中
        const node = this.$refs.tree.getNode(data.id); // getNode(node-key)
        this.selectChildren(data, true); // 选中子节点
        this.parentNodesChange(node); // 选中父节点
      } else {
        this.selectChildren(data, false); // 取消子节点
      }
    },
    selectChildren(data, checked) {
      data && data.children && data.children.map(item => {
        this.$refs.tree.setChecked(item.id, checked);
        if (data.children) {
          this.selectChildren(item, checked);
        }
      });
    },
    // 父级递归
    parentNodesChange(node) {
      // console.log(node);
      if (node.parent) {
        for (const key in node) {
          if (key == "id") {
            // console.log(node[key]);
            this.$refs.tree.setChecked(node, true);
          }
        }
        if (node.parent && node.id !== 0) {
          this.parentNodesChange(node.parent);
        }
      }
    },
    // 关联菜单
    async zzjgSave() {
      const ids = this.$refs.tree.getCheckedKeys();
      // 系统权限与业务权限不能同时授权
      const xtpzcd = this.data.find(el => el.menuName === "系统配置");
      if (xtpzcd) {
        const xtpzcdid = xtpzcd.id;
        const xtpzcdids = [];
        xtpzcd.children.forEach(el => {
          xtpzcdids.push(el.id);
          if (el.children) {
            el.children.forEach(val => {
              xtpzcdids.push(val.id);
            });
          }
        });
        if (ids.includes(xtpzcdid)) {
          const idsCopy = ids.slice(0);
          xtpzcdids.forEach(el => {
            const index = idsCopy.findIndex(id => el === id);
            if (index > -1) {
              idsCopy.splice(index, 1);
            }
          });
          if (idsCopy.length > 1) {
            return this.$message.warning("系统配置和业务权限不能同时配置！");
          }
        }
      }
      //
      const params = ids.map(i => {
        return {
          checkStatus: 0,
          menuId: i,
          roleId: this.roleId
        };
      });
      console.log(params, "---params");
      const res = await batchSave(params);
      console.log(res);
      if (res) {
        this.$message({
          message: "关联成功!",
          type: "success"
        });
      }
    },
    // 查询当前角色关联的菜单
    async getRoleWithMenu() {
      const res = await getMenusByRoleId(this.roleId);
      const ids = res.map(i => {
        return i.id;
      });
      this.$refs.tree.setCheckedKeys(ids);
    }
  }
};
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.UserConfig {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border-radius: 4px;

  .left_table {
    width: 32%;
    height: 100%;
    border-right: 1px solid #eee;
    box-sizing: border-box;
  }

  .right_content {
    flex: 1;
    height: 100%;
    box-sizing: border-box;
    border: 1px solid #eee;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .top_menu {
      width: 100%;
      height: 8%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      box-sizing: border-box;
      border-bottom: 1px solid #eee;

      // background-color: #1890ff;
      .menu_left {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        .check_item {
          box-sizing: border-box;
          margin: 0 30px;
          cursor: pointer;
          color: #303133;
          border-bottom: 3px solid transparent;

          &:hover {
            color: #1890ff;
            font-weight: 600;
          }
        }

        .checkColor {
          color: #1890ff;
          font-weight: 600;
          box-sizing: border-box;
          padding-bottom: 3px;
          border-bottom: 3px solid #1890ff;
        }
      }
    }

    .bottom_main {
      width: 100%;
      // flex: 1;
      height: 92.5%;

      .details_box {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;

        :deep(.el-input__inner) {
          width: 500px;
        }

        :deep(.el-textarea__inner) {
          width: 500px;
        }
      }

      .user_box {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        padding: 5px 20px;

        .top_serch {
          width: 100%;
          height: 14%;
          display: flex;
          justify-content: center;
          align-items: center;

          .serch_leftForm {
            width: 90%;
            height: 100%;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            justify-content: space-between;

            :deep(.el-input__inner) {
              width: 350px;
              height: 32px;
            }

            :deep(.el-form-item__content) {
              line-height: 32px;
            }

            :deep(.el-form-item) {
              margin-bottom: 10px;
            }
          }

          .serch_rightBtn {
            flex: 1;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: flex-start;
          }
        }

        .userList_content {
          width: 100%;
          flex: 1;
          margin-top: 30px;
        }
      }

      .menu_box {
        width: 100%;
        height: 100%;
        display: flex;

        .menu_tree {
          width: 100%;
          height: 100%;
          // padding: 50px;
          display: flex;
          flex-direction: column;
          // justify-content: center;
          // align-items: center;
          box-sizing: border-box;

          .tree_box {
            // flex: 1;
            height: 90%;
            width: 100%;
            padding: 20px 10px;
            box-sizing: border-box;
            overflow: scroll;
          }

          .check_box {
            div {

              font-size: 20px;
              font-weight: 600;
              color: #1890ff;
            }

            padding: 20px;
            box-sizing: border-box;
          }
        }
      }
    }
  }
}

.btnPower {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;

  .tree_box {
    width: 30%;
    height: 95%;
    padding: 30px;
    box-sizing: border-box;
    overflow: scroll;
  }

  .draggable_title {
    // width: 100%;
    font-size: 20px;
    font-weight: 600;
    color: #1890ff;
    margin: 20px 0;
    // text-align: left;
  }

  .draggable_box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .nowBox,
    .boxList {
      // display: inline-block;
      width: 90%;
      // height: 200px;
      border: 1px solid #ccc;
      padding: 10px;
      // margin-right: 10px;
      // vertical-align: top;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      flex-wrap: wrap;
    }

    .nowBox {
      min-height: 15%;
    }

    .boxList {
      flex: 1;
      // margin-top: 5%;
    }

    .item {
      background-color: #3561fd;
      color: #fff;
      border-radius: 15px;
      padding: 10px 15px;
      margin: 5px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      // margin-bottom: 5px;
    }

    .items {
      background-color: #ccc;
      color: #fff;
      border-radius: 15px;
      padding: 10px 15px;
      margin: 5px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      // margin-bottom: 5px;
    }
  }
}
</style>
